<?php

namespace Wechat\Controller;

use Think\Controller;

class ApiController extends Controller {

    /**

     * 微信消息接口入口

     * 所有发送到微信的消息都会推送到该操作

     * 所以，微信公众平台后台填写的api地址则为该操作的访问地址

     */
    public function index($id = '') {

        import("@.Util.Wechat");

        $token = I('get.Token') ? I('get.Token') : C('token'); //微信后台填写的TOKEN

        /* 加载微信SDK */

        $wechat = new \Wechat($token);


        /* 获取请求信息 */

        $data = $wechat->request();

        $data['openid'] = $data['FromUserName'];

        if ($data && is_array($data)) {

            S('weixin', $wechat);

            S('data', $data);
        
            /**

             * 你可以在这里分析数据，决定要返回给用户什么样的信息

             * 接受到的信息类型有9种，分别使用下面九个常量标识

             * Wechat::MSG_TYPE_TEXT       //文本消息

             * Wechat::MSG_TYPE_IMAGE      //图片消息

             * Wechat::MSG_TYPE_VOICE      //音频消息

             * Wechat::MSG_TYPE_VIDEO      //视频消息

             * Wechat::MSG_TYPE_MUSIC      //音乐消息

             * Wechat::MSG_TYPE_NEWS       //图文消息（推送过来的应该不存在这种类型，但是可以给用户回复该类型消息）

             * Wechat::MSG_TYPE_LOCATION   //位置消息

             * Wechat::MSG_TYPE_LINK       //连接消息

             * Wechat::MSG_TYPE_EVENT      //事件消息

             *

             * 事件消息又分为下面五种

             * Wechat::MSG_EVENT_SUBSCRIBE          //订阅

             * Wechat::MSG_EVENT_SCAN               //二维码扫描

             * Wechat::MSG_EVENT_LOCATION           //报告位置

             * Wechat::MSG_EVENT_CLICK              //菜单点击

             * Wechat::MSG_EVENT_MASSSENDJOBFINISH  //群发消息成功

             */
            //根据来源信息的类型使用不同的方法路径进行处理

            Switch ($data['MsgType']) {

                case \Wechat::MSG_TYPE_TEXT: //文本

                    $arr = $this->text($data);
                    $arr['content'] = "抱歉，请您进入<a href='http://".C('WEB_HOST')."/wechat/Messagebox/index'>留言系统</a>进行留言以便我们尽快联系您，请点击<a href='http://".C('WEB_HOST')."/wechat/Messagebox/index'>留言</a>";
                    $arr['type'] = 'text';
                    break;

                case \Wechat::MSG_TYPE_IMAGE: //图片

                    $arr = image($data);

                    break;



                case \Wechat::MSG_TYPE_EVENT: //事件

                    $arr = $this->event($data);
                    
                    break;



                default:

                    $content = "该功能暂未开放"; //回复内容，回复不同类型消息，内容的格式有所不同

                    $type = 'text'; //回复消息的类型
            }

            /////////////////////////////////////////////////////////////////////

            $content = $arr['content'] ? $arr['content'] : $content;

            $type = $arr['type'] ? $arr['type'] : $type;

            /* 响应当前请求(自动回复) */

            S('content', $content);

            if(empty($arr) || !isset($arr) || $arr == null) {
                exit("");
            }
            $wechat->response($content, $type);
            /**

             * 响应当前请求还有以下方法可以只使用

             * 具体参数格式说明请参考文档

             * 

             * $wechat->replyText($text); //回复文本消息

             * $wechat->replyImage($media_id); //回复图片消息

             * $wechat->replyVoice($media_id); //回复音频消息

             * $wechat->replyVideo($media_id, $title, $discription); //回复视频消息

             * $wechat->replyMusic($title, $discription, $musicurl, $hqmusicurl, $thumb_media_id); //回复音乐消息

             * $wechat->replyNews($news, $news1, $news2, $news3); //回复多条图文消息

             * $wechat->replyNewsOnce($title, $discription, $url, $picurl); //回复单条图文消息

             * 

             */
        }
    }

    /////////////////////////////////
    //分支功能

    protected function text($data) {

        switch ($data['Content']) {



            default:

                $arr = null;

                break;
        }

        return $arr;
    }

    protected function event($data) {

        switch ($data['Event']) {

            case \Wechat::MSG_EVENT_SUBSCRIBE:  //关注

                if(!isNullOrEmpty($data["openid"])) {

                    $customer = D("Customer")->queryByMap(array("openid"=>$data["openid"]));

                    if(isNullOrEmpty($customer)) {

                        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".access_token()."&openid=".$data["openid"]."&lang=zh_CN";
                        $info = json_decode(curl($url),true);

                        $nicknameTmp = json_encode($info["nickname"]);
                        $nicknameTmp = preg_replace_callback("#(\\\ud[0-9a-f]{3})#i",function($r){ return ""; },$nicknameTmp);
                        $nicknameNoEmoji = json_decode($nicknameTmp);

                        $customerData["nickname"] = $nicknameNoEmoji;
                        $customerData["openid"] = $data["openid"];
                        $customerData["headimgurl"] = $info["headimgurl"];
                        $customerData["realname"] = $nicknameNoEmoji;
                        $customerData["create_time"] = getCurrentDate();
                        $customerData["subscribe"] = 1;
                        if(!isNullOrEmpty($customerData)) {
                            D("Customer")->add($customerData);
                        }

                    } else {
                        $customer["subscribe"] = 1;
                        $customer["subscribe_time"] = getCurrentDate();
                        D("Customer")->updateInfo($customer);
                    }

                    cookie("openid", $data["openid"]);

                }

//                $arr['content'] = "欢迎关注希卫康
//
//请选择您关心的疾病
//
//<a href='http://".C('WEB_HOST')."/wechat/userCenter/myInfo/categoryId/2'>马蹄内翻足</a>
//<a href='http://".C('WEB_HOST')."/wechat/userCenter/myInfo/categoryId/1'>下肢慢创、水肿、糖尿病足</a>
//<a href='http://".C('WEB_HOST')."/wechat/userCenter/myInfo/categoryId/3'>踝关节运动防护</a>
//<a href='http://".C('WEB_HOST')."/wechat/userCenter/myInfo/categoryId/5'>儿童先天髋关节发育不良</a>
//<a href='http://".C('WEB_HOST')."/wechat/userCenter/myInfo/categoryId/6'>踝关节不稳定</a>
//<a href='http://".C('WEB_HOST')."/wechat/userCenter/myInfo/categoryId/4'>脑瘫及运动系统发育疾病</a>
//<a href='http://".C('WEB_HOST')."/wechat/userCenter/myInfo/categoryId/7'>脊柱畸形</a>
//<a href='http://".C('WEB_HOST')."/wechat/userCenter/myInfo/categoryId/8'>脑卒中（中风）</a>
//
//电话咨询：13901028635
//
//也可以点击<a href='http://".C('WEB_HOST')."/wechat/userCenter/messagebox'>留言</a>，我们将尽快联系您
//";

                $arr['content'] = "欢迎关注希卫康

患有行动能力障碍的人，是一个特殊群体，直接影响着身边人群的社会参与和生活质量。希卫康励志帮助更多行动能力障碍者回归社会，做连接他们与社会的桥梁。截止到目前，我们已经帮助了上千位不同类型的患者，例如脑瘫、马蹄足、脊柱侧弯、中风、截肢等等。

您可以给我们<a href='http://".C('WEB_HOST')."/wechat/Messagebox/index'>留言</a>

免费评估点击<a href='http://".C('WEB_HOST')."/wechat/case'>病例专区</a>

如需支付点击<a href='http://".C('WEB_HOST')."/wechat/payment'>付款</a>

";

                $arr['type']    = 'text'; //回复消息的类型

                break;

            case unsubscribe:  //取消关注

                $customer = D("Customer")->queryByMap(array("openid"=>$data["openid"]));

                $customer["subscribe"] = 0;
                D("Customer")->updateInfo($customer);

                cookie("openid", null);

                break;


            default:

                //$arr['content'] = $data['Event']."事件暂未开放"; //回复内容，回复不同类型消息，内容的格式有所不同
                //$arr['type']    = 'text'; //回复消息的类型

                $arr = null;

                break;
        }

        return $arr;
    }

    protected function click($data) {

        switch ($data['EventKey']) {

            default:

                $arr['content'] = "该功能暂未开放"; //回复内容，回复不同类型消息，内容的格式有所不同

                $arr['type'] = 'text'; //回复消息的类型

                break;
        }



        return $arr;
    }

    protected function image($data) {

        $arr['content'] = "你是说：" . $data['Content']; //回复内容，回复不同类型消息，内容的格式有所不同

        $arr['type'] = 'text'; //回复消息的类型

        return $arr;
    }

    /////////////////////////////
    //自定义菜单功能



    function menulist() {

        echo $url = 'https://api.weixin.qq.com/cgi-bin/menu/get?access_token=' . access_token();

        //$post = array(124,535,635,42);

        $arr = json_decode(curl($url), true);

        dump($arr);

        echo "<br/>";

        dump(json_encode($arr));
    }

    function menuadd() {

        if (I('get.key') != 'luoe123') {

            exit("参数错误");
        }

        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . access_token();

        $data = resetMenu();

        $aaa = curl($url, $data);

    }

    //////////////////////////////////
    /// view获取openid



    function auth() {

        //dump(I('get.'));

        $state = I('get.state');

        $pstr = I('get.pstr');
        $code = I('get.code');

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . C('appid') . "&secret=" . C('appsecret') . "&code=" . $code . "&grant_type=authorization_code";

        $r = json_decode(curl($url), true);

        //dump($r);

        $openid = $r['openid'];

        $db = M('user');

        $sql = $db->where("openid = '$openid'")->find();

        cookie('uid', $sql['uid'], 0);
        
        cookie('openid', $sql['openid'], 0);
 
    }

    function auth2() {

        $code = '04143f67c046f5e587ae729d6cbef9fH';

        echo $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . C('appid') . "&secret=" . C('appsecret') . "&code=" . $code . "&grant_type=authorization_code";

        $r = json_decode(curl($url), true);

        dump($r);
    }

    function auth3() {

        $state = I('get.state');

        $code = I('get.code');
                
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . C('appid') . "&secret=" . C('appsecret') . "&code=" . $code . "&grant_type=authorization_code";

        $r = json_decode(curl($url), true);

        $openid = $r['openid'];

        if(!isNullOrEmpty($r["openid"])) {

            $customer = D("Customer")->where(array("openid"=>$openid))->find();

            if(isNullOrEmpty($customer)) {
                $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $r['access_token'] . "&openid=" . $openid . "&lang=zh_CN";
                $r = json_decode(curl($url), true);

                $nicknameTmp = json_encode($r["nickname"]);
                $nicknameTmp = preg_replace_callback("#(\\\ud[0-9a-f]{3})#i",function($r){ return ""; },$nicknameTmp);
                $nicknameNoEmoji = json_decode($nicknameTmp);

                $customerData["nickname"] = $nicknameNoEmoji;
                $customerData["openid"] = $r["openid"];
                $customerData["headimgurl"] = $r["headimgurl"];
                $customerData["create_time"] = getCurrentDate();
                if(!isNullOrEmpty($customerData)) {
                    $customer = D("Customer")->where(array("openid"=>$openid))->find();
                    if(isNullOrEmpty($customer)) {
                        D("Customer")->add($customerData);
                    }
                }
            }
            cookie("openid", $r["openid"], 3600 * 24 * 30);
        }
        
        header("Location: " . urldecode($state));
    }

    ///////////////////////////
    //客服消息

    function send($openid, $text) {

        //$uid = I('get.openid');
        //$text = I('post.text');
        //$uid = 'ozj3Us5MtH-WdZJ8cvZWfYMuj4CQ';

        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . access_token();

        $post = array(
            "touser" => $openid,
            "msgtype" => "text",
            "text" => array(
                "content" => $text,
            ),
        );

        $data = json_encode2($post);

        $aaa = curl($url, $data);

        return $aaa;
    }

    /////////////////////////
    //用户功能

    function userlist() {

        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" . access_token();
        if (I('get.openid')) {
            $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" . access_token() . "&next_openid=" . I('get.openid');
        }
        $arr = curl($url);

        $arr2 = json_decode($arr, true);

        S('Wechat_user_list', $arr2[data][openid]);

        dump($arr2[data][openid]);
    }

    /////////////////////////////////////////
    //短信

    protected function sms($tel, $content) {

        $ch = curl_init();



        curl_setopt($ch, CURLOPT_URL, "http://sms-api.luosimao.com/v1/status.json");

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

        curl_setopt($ch, CURLOPT_HEADER, FALSE);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);



        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

        curl_setopt($ch, CURLOPT_USERPWD, 'api:key-' . C('mmskey'));



        $res = curl_exec($ch);

        curl_close($ch);

        //$res  = curl_error( $ch );

        dump($res);
    }

    protected function sendPicTextData($data) {
        $ArticleCount = 1;
        $newsTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<ArticleCount>%s</ArticleCount>
						<Articles>
							<item>
								<Title><![CDATA[%s]]></Title>
								<Description><![CDATA[%s]]></Description>
								<PicUrl><![CDATA[%s]]></PicUrl>
								<Url><![CDATA[%s]]></Url>
							</item>
						</Articles>
					</xml>";

        $resultStr = sprintf($newsTpl, $data['FromUserName'], $data['ToUserName'], time(), 'news', $ArticleCount, '测试图文标题', '测试图文内容', 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png', 'http://www.baidu.com');
        return $resultStr;
    }

    public function debugWechatPay() {

        echo C('rooturl') . U('/Wechat/Api/WechatPay?orderId=1');

    }

    public function handlePayOrder() {

        $order = $GLOBALS['HTTP_RAW_POST_DATA'];

        if(!$order){
            $order = file_get_contents("php://input");
        }

        $array_data = json_decode(json_encode(simplexml_load_string($order, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        if ($array_data['return_code'] == 'SUCCESS') {

            echo 'SUCCESS';

            //查找支付记录
            $payMap['out_trade_no'] = $array_data['out_trade_no'];
            $pay = D('Pay')->where($payMap)->find();

            if(isNullOrEmpty($pay["status"])) {

                //修改支付记录
                $payData['status'] = 1;
                $payData['update_time'] = getCurrentDate();
                $payData['pay_trade_no'] = $array_data['transaction_id'];

                D('Pay')->where($payMap)->save($payData);

                if($pay['type'] == 0){
                    //查找订单
                    $paymentMap['pay_id'] = $pay['pay_id'];
                    $payment = D("Payment")->where($paymentMap)->find();

                    //修改订单状态
                    $payment["status"] = C("ORDER_STATUS.WAITING_HANDLE");
                    $payment["pay_time"] = getCurrentDate();
                    D('Payment')->updateInfo($payment);

                    $customer = D("Customer")->queryById($payment["customer_id"]);
//                    $product = D("Product")->queryById($payment["product_id"]);

                    //推送预约信息到管理员
                    $paymentSuccessData["title"] = $customer["nickname"]
                        .",通过公众号收款链接付款";
                    $paymentSuccessData["orderNumber"] = $pay["out_trade_no"];
                    $paymentSuccessData["price"] = $pay["money"]."元 " .$customer["nickname"];
                    $remark = "";
                    if(!isNullOrEmpty($payment["name"])){
                        $remark = $remark . "姓名:" . $payment["name"] . "；";
                    }

//                    if(!isNullOrEmpty($payment["number"])){
//                        $remark = $remark . "电话:" . $payment["number"] . "；";
//                    }
//                    if(!isNullOrEmpty($payment["sales_id"])){
//                        $sales = D("Employee")->queryById($payment["sales_id"]);
//                        $remark = $remark . "销售:" . $sales["employee_name"] . "；";
//                    }
                    if(!isNullOrEmpty($payment["payment_content"])){
                        $remark = $remark . "备注:" . $payment["payment_content"] . "；";
                    }
                    if($payment["need_invoice"] == 1){
                        $remark = $remark . "开公司发票";
                    }
                    if($payment["need_invoice"] == 2){
                        $remark = $remark . "开个人发票";
                    }
                    if($payment["type"] == "wangjing"){
                        $paymentSuccessData["title"] = $customer["nickname"]
                            .",通过[望京医院二维码]付款";
                        if(!isNullOrEmpty($payment["receive_contact"]))
                            $remark = $remark . "，电话：".$payment["receive_contact"];
                    }
                    $paymentSuccessData["remark"] = $remark;
                    $paymentSuccessData["url"] = "http://".C('WEB_HOST')."/wechat/payment/paymentList/?id=". $payment["payment_id"];
//                    $adminRoleArr = array("1","3","4","8","10");
//                    $openidArray = getNotifyArr($adminRoleArr, "xWk202003270001");
                    $openidArray = getNotifyArrByName("paymentSuccess", "xWk202003270001");
                    $openidArray = array_unique($openidArray);
                    foreach ($openidArray as $openid) {
                        $paymentSuccessData["openid"] = $openid;
                        paymentSuccessNotify($paymentSuccessData);
                    }
                    if($payment["type"] == "wangjing"){
                        $openidArrayWanjing = getNotifyArrByName("paymentSuccessWangjing", "xWk202003270001");
                        foreach ($openidArrayWanjing as $openid) {
                            $paymentSuccessData["openid"] = $openid;
                            paymentSuccessNotify($paymentSuccessData);
                        }
                    }

                    $paymentSuccessData["title"] = "您已通过公众号收款链接付款成功";
                    if($payment["type"] == "wangjing"){
                        $paymentSuccessData["title"] = $customer["nickname"]
                            .",您已通过望京医院二维码付款成功";
                    }
                    $paymentSuccessData["url"] = "http://".C('WEB_HOST')."/wechat/userCenter/myPayment";
                    $paymentSuccessData["openid"] = $customer["openid"];
                    paymentSuccessNotify($paymentSuccessData);
                }

                if($pay['type'] == 1){
                    //查找订单
                    $productOrderMap['pay_id'] = $pay['pay_id'];
                    $productOrder = D("Order")->where($productOrderMap)->find();

                    //修改订单状态
                    $productOrder["status"] = C("ORDER_STATUS.WAITING_HANDLE");
                    $productOrder["pay_time"] = getCurrentDate();
                    D('Order')->updateInfo($productOrder);

                    $customer = D("Customer")->queryById($productOrder["customer_id"]);
                    $product = D("Product")->queryById($productOrder["product_id"]);

                    //推送预约信息到管理员
                    $orderSuccessData["title"] = $customer["nickname"]
                        ."刚刚购买并支付了".$productOrder["number"]."件".$product["product_name"]."，请核对信息后及时安排相关事项";
                    $orderSuccessData["orderNumber"] = $pay["out_trade_no"];
                    $orderSuccessData["price"] = $pay["money"]."元 ".$customer["nickname"]."购买[".$product["product_name"]."]".$productOrder["number"]."件";
                    if(!isNullOrEmpty($productOrder["coupon_code"])){
                        $orderSuccessData["remark"] = "CP码：".$productOrder["coupon_code"];
                        $orderSuccessData["orderNumber"] .= " CP码：".$productOrder["coupon_code"];
                        if(!isNullOrEmpty($productOrder["doctor_name"])){
                            $orderSuccessData["remark"] .= "，医生：" . $productOrder["doctor_name"];
                        }
                        if(!isNullOrEmpty($productOrder["hospital_name"])){
                            $orderSuccessData["remark"] .= "，医院：" . $productOrder["hospital_name"];
                        }
                        $orderSuccessData["remark"] .= "，联系人：" . $productOrder["patient_name"];
                        if(!isNullOrEmpty($productOrder["note"])){
                            $orderSuccessData["remark"] .= "，客户留言：" . $productOrder["note"];
                        }
                        $couponOrder = D("Coupon")->where(array("coupon_code" => $productOrder["coupon_code"]))->find();
                        $couponHospital = D("CouponHospital")->where(array('coupon_hospital_id'=>$couponOrder["coupon_hospital_id"]))->find();
                        $cpopenidArray = getNotifyArrByName("cpOrderSuccess".$couponHospital["coupon_hospital_code"], "xWk202003270001");
                        $cpopenidArray = array_unique($cpopenidArray);
                        foreach ($cpopenidArray as $openid) {
                            $orderSuccessData["openid"] = $openid;
                            orderSuccessNotify($orderSuccessData);
                        }
                    }else{
                        $orderSuccessData["remark"] = "希卫康系统自动推送";
                    }


//                    $adminRoleArr = array("1","8","10");
//                    $openidArray = getNotifyArr($adminRoleArr, "xWk202003270001");
                    $openidArray = getNotifyArrByName("orderSuccess", "xWk202003270001");
                    $openidArray = array_unique($openidArray);
                    foreach ($openidArray as $openid) {
                        $orderSuccessData["openid"] = $openid;
                        orderSuccessNotify($orderSuccessData);
                    }

                    //推送信息
                    $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/userCenter/myOrder?status=0";
                    $notifyData["first"] = "您的订单已付款成功";
                    $notifyData["keyword1"] = $pay["money"]."元";
                    $notifyData["keyword2"] = $product["product_name"]."[".$productOrder["size"]."]，共 ".$productOrder["number"]." 件";
                    $notifyData["keyword3"] = $productOrder["receive_address"]." ".$productOrder["receive_name"]." ".$productOrder["receive_contact"];
                    $notifyData["keyword4"] = $pay["out_trade_no"];
                    $notifyData["remark"] = "点击查看订单详情。";

                    $notifyData["openid"] = $customer["openid"];
                    OrderPaidNotify($notifyData);
                }

                if($pay['type'] == 2){
                    //查找订单
                    $quickOrderMap['pay_id'] = $pay['pay_id'];
                    $quickOrder = D("QuickOrder")->where($quickOrderMap)->find();

                    //修改订单状态
                    $quickOrder["status"] = -1;
                    $quickOrder["pay_time"] = getCurrentDate();
                    D('QuickOrder')->updateInfo($quickOrder);

                    $customer = D("Customer")->queryById($quickOrder["customer_id"]);
                    $product = D("FinishedProduct")->queryById($quickOrder["finished_product_id"]);

//                    $adminRoleArr = array("1","8","10");
//                    $openidArray = getNotifyArr($adminRoleArr, "xWk202003270001");
                    $openidArray = getNotifyArrByName("orderSuccess", "xWk202003270001");

                    $openidArray = array_unique($openidArray);
                    foreach ($openidArray as $openid) {
                        $orderSuccessData["openid"] = $openid;
                        quickOrderSuccessNotify($orderSuccessData);
                    }
                    $orderSuccessData["orderNumber"] = $pay["out_trade_no"];
                    $orderSuccessData["price"] = $pay["money"]."元";
                    $orderSuccessData["title"] = "您刚刚购买并支付了" . $quickOrder["number"] . "件" . $product["name"] . "，请等待发货通知。";
                    $orderSuccessData["openid"] = $customer["openid"];
                    quickOrderSuccessNotify($orderSuccessData);
                }

                if($pay['type'] == 3){
                    //查找订单
                    $finishedOrderMap['pay_id'] = $pay['pay_id'];
                    $finishedOrder = D("FinishedOrder")->where($finishedOrderMap)->find();

                    //修改订单状态
                    $finishedOrder["status"] = -1;
                    $finishedOrder["pay_time"] = getCurrentDate();
                    D('FinishedOrder')->updateInfo($finishedOrder);

                    $customer = D("Customer")->queryById($finishedOrder["employee_id"]);
                    $product = D("FinishedProduct")->queryById($finishedOrder["finished_product_id"]);

                    $orderSuccessData["url"] = "http://".C('WEB_HOST')."/wechat/finishedProduct/orderList/?id=". $finishedOrder["finished_order_id"];
                    $orderSuccessData["orderNumber"] = $finishedOrder["finished_order_no"];
                    $orderSuccessData["price"] = $pay["money"]."元";
                    $orderSuccessData["title"] = "您刚刚支付了" . $finishedOrder["number"] . "件" . $product["name"] ."产品(".$finishedOrder["size"] .") 请等待发货通知。";
                    $orderSuccessData["openid"] = $customer["openid"];
                    quickOrderSuccessNotify($orderSuccessData);

                    $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/finishedProduct/orderList/?id=". $finishedOrder["finished_order_id"];
                    $notifyData["first"] = "收到分销成品订单。";
                    if(!isNullOrEmpty($finishedOrder["patient_name"])){
                        $notifyData["first"] .= "患者：" . $finishedOrder["patient_name"];
                    }
                    $notifyData["keyword1"] = $finishedOrder["finished_order_no"];
                    if(!isNullOrEmpty($finishedOrder["patient_name"])){
                        $notifyData["keyword1"] .= ", 患者：" . $finishedOrder["patient_name"];
                    }
                    $notifyData["keyword2"] = $finishedOrder["name"]."(".$finishedOrder["size"] .")共 ".$finishedOrder["number"]." 件";
                    $notifyData["keyword3"] = $finishedOrder["create_time"];
                    $notifyData["keyword4"] = $finishedOrder["total_price"];
                    if(!isNullOrEmpty($finishedOrder["agent_name"])){
                        $notifyData["keyword4"] .= " [" . $finishedOrder["agent_name"] ."]";
                    }
                    $user = D("admin")->where(array('employee_id'=>$finishedOrder["employee_id"]))->find();
                    $notifyData["keyword5"] = "[" . $finishedOrder["delivery_type"]."] 下单人：".$user["admin_name"]."(".$finishedOrder["payment_type"].")";
                    $notifyData["remark"] = $finishedOrder["note"];

                    $openidArray = getNotifyArrByName("createFinishedOrder", $user["enterprise_code"]);
                    array_push($openidArray, $user["openid"]);
                    $openidArray = array_unique($openidArray);
                    foreach ($openidArray as $openid) {
                        $notifyData["openid"] = $openid;
                        finishedOrderNotify($notifyData);
                    }
                }
            }

        }

    }

    public function handlePayBooking() {

        $order = $GLOBALS['HTTP_RAW_POST_DATA'];

        if(!$order){
            $order = file_get_contents("php://input");
        }

        $array_data = json_decode(json_encode(simplexml_load_string($order, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        if ($array_data['return_code'] == 'SUCCESS') {

            echo 'SUCCESS';

            //查找支付记录
            $payMap['out_trade_no'] = $array_data['out_trade_no'];
            $pay = D('Pay')->where($payMap)->find();

            if(isNullOrEmpty($pay["status"])) {

                //修改支付记录
                $payData['status'] = 1;
                $payData['update_time'] = getCurrentDate();
                $payData['pay_trade_no'] = $array_data['transaction_id'];

                D('Pay')->where($payMap)->save($payData);

                //查找订单
                $bookingMap['pay_id'] = $pay['pay_id'];
                $booking = D("Booking")->where($bookingMap)->find();

                //修改订单状态
                $booking["status"] = C("BOOKING_STATUS.WAITING_SERVICE");

                D('Booking')->updateInfo($booking);

                //修改预约人数
                $logMap["product_id"] = $booking["product_id"];
                $logMap["day"] = $booking["booking_time"];
                $bookingLog = D("BookingLog")->where($logMap)->find();

                if(isNullOrEmpty($bookingLog)) {

                    $logData["product_id"] = $booking["product_id"];
                    $logData["day"] = $booking["booking_time"];
                    $logData["status"] = 1;
                    $logData["number"] = 1;
                    $logData["create_time"] = getCurrentDate();
                    $logData["shop_id"] = $booking["location_type"];

                    D("BookingLog")->add($logData);

                } else {

                    if($bookingLog["number"] >= 3) {
                        $bookingLog["status"] = -1;
                    }

                    $bookingLog["number"] = $bookingLog["number"] + 1;

                    D("BookingLog")->updateInfo($bookingLog);

                }

                $product = D("Product")->queryById($booking["product_id"]);

                //推送预约信息到管理员
                $bookingSuccessData["title"] = $booking["name"]
                    ."刚刚预约了".$booking["booking_time"]."到指定地址进行测量检查，相关产品是".$product["product_name"];
                $bookingSuccessData["orderNumber"] = $booking["booking_id"];
                $bookingSuccessData["price"] = $pay["money"]."元";
                $bookingSuccessData["remark"] = "希卫康系统自动推送";

                $adminRoleArr = array("1","3");
                $openidArray = getNotifyArr($adminRoleArr, "xWk202003270001");
                $openidArray = array_unique($openidArray);
                foreach ($openidArray as $openid) {
                    $bookingSuccessData["openid"] = $openid;
                    orderSuccessNotify($bookingSuccessData);
                }

            }

        }

    }

    public function handlePayActivity() {

        $order = $GLOBALS['HTTP_RAW_POST_DATA'];

        if(!$order){
            $order = file_get_contents("php://input");
        }

        $array_data = json_decode(json_encode(simplexml_load_string($order, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        if ($array_data['return_code'] == 'SUCCESS') {

            echo 'SUCCESS';

            //查找支付记录
            $payMap['out_trade_no'] = $array_data['out_trade_no'];
            $pay = D('Pay')->where($payMap)->find();

            if(isNullOrEmpty($pay["status"])) {

                //修改支付记录
                $payData['status'] = 1;
                $payData['update_time'] = getCurrentDate();
                $payData['pay_trade_no'] = $array_data['transaction_id'];

                D('Pay')->where($payMap)->save($payData);

                //查找订单
                $joinMap['pay_id'] = $pay['pay_id'];
                $join = D("ActivityJoin")->where($joinMap)->find();

                //修改订单状态
                $join["status"] = C("ACTIVITY_JOIN_STATUS.END_PAY");

                D('ActivityJoin')->updateInfo($join);

                //修改已经报名人数
                $paidMap["activity_id"] = $join["activity_id"];
                $paidMap["status"] = C("ACTIVITY_JOIN_STATUS.END_PAY");
                $paidCount = D("ActivityJoin")->where($paidMap)->count();

                $activity = D("Activity")->queryById($join["activity_id"]);

                $activity["join_number"] = $paidCount;

                if($activity["upper_limit"] <= $paidCount
                    && $activity["status"] == C("ACTIVITY_STATUS.WAITING_JOIN")) {
                    $activity["status"] = C("ACTIVITY_STATUS.FULL");
                }

                D("Activity")->updateInfo($activity);

                //推送预约信息到管理员
                $joinSuccessData["title"] = $join["name"]
                    ."刚刚报名并支付了我公司组织的活动".$activity["title"];
                $joinSuccessData["orderNumber"] = $pay["out_trade_no"];
                $joinSuccessData["price"] = $activity["price"]."元";
                $joinSuccessData["remark"] = "希卫康系统自动推送";

                $adminRoleArr = array("1","3");
                $openidArray = getNotifyArr($adminRoleArr, "xWk202003270001");
                $openidArray = array_unique($openidArray);
                foreach ($openidArray as $openid) {
                    $joinSuccessData["openid"] = $openid;
                    orderSuccessNotify($joinSuccessData);
                }

            }

        }

    }

    public function notice(){
        if(date("w") == 0 || date("w") == 6){
            return false;
        }
        $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/hospitalProduct/notice";
        $notifyData["first"] = "每日提醒";
        $notifyData["keyword1"] = "《跟刀整改措施及规范》";
        $weekarray=array("日","一","二","三","四","五","六"); //先定义一个数组
        $notifyData["keyword2"] = date("Y-m-d") . "【星期".$weekarray[date("w")] ."】";
        $notifyData["keyword3"] = "请仔细阅读";
        $notifyData["remark"] = "点击查看规范详情";
//        $notifyData["openid"] = "otBeowu8bYi2HBRTMBWSIWzzkkbo";//zjx
        $openidArray = getNotifyArrByName("hopitalOperationNotice", "xWk202003270001");

        $openidArray = array_unique($openidArray);
        foreach ($openidArray as $openid) {
            $notifyData["openid"] = $openid;
            groupNotify($notifyData);
        }
    }

    public function clubfootSchedule(){
//        echo(date('Y-m-01', strtotime('-1 month')));
//        echo(date('Y-m-01', strtotime(date("Y-m-d"))));
        $map = array();
//        $map["cl.checkin_time-egt"] = date('Y-m-01', strtotime('-1 month')) . " 00:00:00";
        $map["cl.checkin_time"]  = array('egt',date('Y-m-01', strtotime('-1 month')) . " 00:00:00");
//        $map["cl.checkin_time"]  = array('egt',"2021-06-28 23:00:00");
        $list = D("ClubfootLog")->alias("cl")
//            ->join("left join __CUSTOMER__ c on c.customer_id = cl.customer_id")
            ->where($map)
            ->order("cl.customer_id asc")
            ->field("cl.*")
            ->select();
//        echo(sizeof($list));
        $customerList = array();
        foreach ($list as $item) {
            if($item["checkin_type"] == 1){
                $customerList[$item["customer_id"]]["start"] += 1;
            }
            if($item["checkin_type"] == 0){
                $customerList[$item["customer_id"]]["end"] += 1;
            }
        }
//        echo(sizeof($customerList));
        $qualifiedList = array();

        foreach ($customerList as $key => $value) {
//            echo($key . "_" . $value["start"]. "_" . $value["end"].";");
            if($value["start"] > 10 && $value["end"] > 10){
                $value["customer_id"] = $key;
                array_push($qualifiedList, $value);
            }
        }
        $updateMonth = date('Y-m', strtotime('-1 month'));
//        echo($updateMonth);
        $number = 0;
        $customer_id_list = "";
        $nickname_list = "";
        $point_list = "";
        $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/clubfoot/myIcoin";
        $notifyData["first"] = "IOWA支具穿戴打卡爱币积分奖励";
//        $notifyData["keyword2"] = getCurrentDate();
        $notifyData["keyword2"] = $updateMonth." 月打卡";
//        $notifyData["keyword4"] = "＋50";

        foreach ($qualifiedList as $qualified) {
            $customer = D("Customer")->queryById($qualified["customer_id"]);
           if( $customer["update_month"] == $updateMonth){
                continue;
            }
            $customer["point"] += 50;
            $customer["update_month"] = $updateMonth;
            D("Customer")->updateInfo($customer);
            if(!isNullOrEmpty($customer_id_list)){
                $customer_id_list .= ",";
                $nickname_list .= ",";
                $point_list .= ",";
            }
            $customer_id_list .= $customer["customer_id"];
            $nickname_list .= $customer["nickname"];
            $point_list .= $customer["point"];
            $number += 1;

            $notifyData["keyword1"] = "微信用户：".$customer["nickname"]."，积分＋50";
//            $notifyData["keyword5"] = $customer["point"];
            $notifyData["remark"] = "当前积分：".$customer["point"];
            $notifyData["openid"] = $customer["openid"];
            pointChangeNotify($notifyData);
        }

        $id = D("ClubfootQualified")->add(array(
            'update_month' => $updateMonth,
            'number' => $number,
            'customer_id_list' => $customer_id_list,
            'nickname_list' => $nickname_list,
            'point_list' => $point_list,
            'create_time' => getCurrentDate(),
        ));

        $groupnotifyData["url"] = "http://".C('WEB_HOST')."/wechat/clubfoot/notify/id/".$id ;
//        $groupnotifyData["first"] = "马蹄足打卡加分报告";
        $groupnotifyData["keyword1"] = "马蹄足打卡每月奖励报告";
        $groupnotifyData["keyword2"] = getCurrentDate();
        $groupnotifyData["keyword3"] = "【" .$updateMonth ."】共 " .$number. " 人";
        $groupnotifyData["remark"] = "点击查看详情";
        $openidArray = getNotifyArrByName("clubfootQualifiedNotice", "xWk202003270001");

        $openidArray = array_unique($openidArray);
        foreach ($openidArray as $openid) {
            $groupnotifyData["openid"] = $openid;
            groupNotify($groupnotifyData);
        }
    }

    public function overdueSchedule(){
        $map["so.status"] = -1;
        $map["so.payment_type"] = "预付";
        $list = D("SpecialOrder")->alias("so")
            ->join("left join __SPECIAL_PRODUCT__ sp on sp.special_product_id = so.special_product_id")
            ->join("left join __ADMIN__ e on e.employee_id = so.employee_id")
            ->where($map)
            ->field("so.*, e.admin_name, sp.name")
            ->select();

        foreach ($list as $specialOrderData) {
            $overdueDays=floor((strtotime(getCurrentDate())-strtotime($specialOrderData["create_time"]))/86400);
            if($overdueDays < 3 || $overdueDays <= $specialOrderData["overdue_days"])
                continue;
            $notifyData["url"] = "http://" . C('WEB_HOST') . "/wechat/specialProduct/orderList/?id=" . $specialOrderData["special_order_id"];
            $notifyData["first"] = "医院定制订单预付款未结清。";
            if (!isNullOrEmpty($specialOrderData["patient_name"])) {
                $notifyData["first"] .= "患者：" . $specialOrderData["patient_name"] . "，ID：" . $specialOrderData["patient_id"] . "，科室：" . $specialOrderData["room"] . "，医生：" . $specialOrderData["doctor_name"];
            }
            $notifyData["keyword1"] = $specialOrderData["name"] . "共 " . $specialOrderData["number"] . " 件";
            if (!isNullOrEmpty($specialOrderData["agent_name"])) {
                $notifyData["keyword1"] .= " [" . $specialOrderData["agent_name"] . "]";
            }
            $notifyData["keyword2"] = $specialOrderData["special_order_no"] . " (" . $specialOrderData["create_time"] . ")";

            $overdueMount = $specialOrderData["total_price"] - $specialOrderData["prepayment"];
            $notifyData["keyword3"] = $specialOrderData["total_price"]. "，欠款￥" . $overdueMount . " (" . $overdueDays . "天)";

            $notifyData["remark"] =  "支具师：" . $specialOrderData["prosthetist_name"] . "，下单人：" . $specialOrderData["admin_name"];
            if(!isNullOrEmpty($specialOrderData["note"])){
                $notifyData["remark"] .= "，备注：" . $specialOrderData["note"];
            }

            $openidArray = getNotifyArrByName("specialOrderOverdue", "xWk202003270001");
            $openidArray = array_unique($openidArray);
            foreach ($openidArray as $openid) {
                $notifyData["openid"] = $openid;
                OrderUnpaidNotify($notifyData);
            }
            $specialOrderData["overdue_days"] = $overdueDays;
            D("SpecialOrder")->updateInfo($specialOrderData);
        }
    }

    public function registerBraceformer(){
        $response = array("result" => "braceform");
        $register = D("Register")->where(array("id" => 1))->select();
//        $register = D("Register")->queryById(1);
        echo($register[0]["code"]);

        return json_encode($response);
    }

    public function loginBraceformer(){
        M("login")->add(array(
            'company' => $_REQUEST["company"],
            'ip' => $_REQUEST["ip"],
            'city' => $_REQUEST["city"],
            'machine_code' => $_REQUEST["machinecode"],
            'version' => $_REQUEST["version"],
            'mac' => $_REQUEST["mac"],
            'create_time' => getCurrentDate(),
        ));

    }
}
